import React from "react";
import ReactDOM from "react-dom";

// useReducer原理实现
let lastState;
function useReducer(reducer, initialState) {
  lastState = lastState || initialState;
  function dispatch(action) {
    // reducer函数执行后会返回一个新的处理过的数据
    lastState = reducer(lastState, action);
    render();
  }
  return [lastState, dispatch];
}

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return state + 1;
    case "decrement":
      return state - 1;
    default:
      return state;
  }
}
function App() {
  let [state, handle] = useReducer(reducer, 0);
  return (
    <div>
      <p>{state}</p>
      <button onClick={() => handle({ type: "increment" })}>add</button>
      <button onClick={() => handle({ type: "decrement" })}>-</button>
    </div>
  );
}
function render() {
  ReactDOM.render(<App />, document.getElementById("root"));
}
render();